package com.qianji.petmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.qianji.common.to.es.SkuEsModel;
import com.qianji.petmall.search.config.PetmallElasticSearch;
import com.qianji.petmall.search.constant.ESConstant;
import com.qianji.petmall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liang zai
 * @date 2022/2/10 12:15
 * @description
 */
@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    private RestHighLevelClient client;
    @Override
    public boolean saveProduct(List<SkuEsModel> list) throws IOException {
        //给es创建一个索引 product
        BulkRequest request = new BulkRequest();

        for (SkuEsModel skuEsModel : list) {
            IndexRequest indexRequest = new IndexRequest(ESConstant.PRODUCT_INDEX).id(skuEsModel.getSkuId().toString());
            String jsonString = JSON.toJSONString(skuEsModel);
            indexRequest.source(jsonString, XContentType.JSON);
            request.add(indexRequest);
        }
        // TODO 发送数据 批量保存
        BulkResponse bulk = client.bulk(request, PetmallElasticSearch.COMMON_OPTIONS);
        // TODO 是否有错
        boolean b = bulk.hasFailures();
        if (b){
            List<String> collect = Arrays.stream(bulk.getItems()).map(item -> item.getId()).collect(Collectors.toList());
            log.error("保存商品异常{}",collect);
        }
        return b;

    }
}
